package cn.com.twoke.easyproject.modules.auth.service.impl;

import cn.com.twoke.easyproject.common.utils.IpUtils;
import cn.com.twoke.easyproject.common.utils.ServletUtils;
import cn.com.twoke.easyproject.modules.auth.event.UserLogoutEvent;
import cn.com.twoke.easyproject.modules.auth.service.LogoutService;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LogoutServiceImpl implements LogoutService {

    private final ApplicationEventPublisher publisher;

    @Override
    public void logout() {
        long loginId = StpUtil.getLoginIdAsLong();
        publishLogoutEvent(loginId);
        StpUtil.logout(loginId);
    }

    /**
     * 发布用户登出事件
     * @param uid
     */
    private void publishLogoutEvent(long uid) {
        String ip = IpUtils.getIp(ServletUtils.getRequest());
        String ip2region = IpUtils.getIp2region(ip);
        publisher.publishEvent(new UserLogoutEvent(this, uid, ip, ip2region));
    }

}
